package ynny.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynny.dao.IUserDao;
import ynny.entity.R;
import ynny.entity.User;
import ynny.service.UserService;

@RestController
@RequestMapping("/user")
public class UserContorller {
    @Autowired
    IUserDao userDao;
    @Autowired
    UserService userService;
    @GetMapping("/{id}")
    public R get(@PathVariable(name = "id") Integer id){

        System.out.println("查询用户ID："+id);

        User user = userDao.findById(id);


        return R.ok(user);
    }
    @RequestMapping("/login")
    public R login(
            @RequestBody User user){
        User users = userDao.login(user.getUsername(), user.getPassword());

        return R.ok(users);
    }
    @RequestMapping("/register")
    public R register(@RequestBody User user){
        if (user.getUsername() == null || user.getPassword() == null){
            return R.fail(211,"用户名或密码不能为空");
        }

        int i = userService.register(user);
        if (i == 201){
            return R.fail(201,"用户名重复");
        }
        return R.ok(user);

    }


    @RequestMapping("/list")
    public R findAll(){
        List<User> users = userDao.findAll();
        return R.ok(users);
    }
    @RequestMapping("/add")
    public R addPaper(@RequestBody User user){
        int i = userDao.add(user);
        if (i > 0){
            return R.ok(user);
        }
        return R.ok(null);
    }
    @RequestMapping("/update")
    public R updatePaper(@RequestBody User user){
        int i = userDao.update(user);
        if (i > 0){
            return R.ok(user);
        }
        return R.ok(null);
    }
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable(name = "id") Integer id ){

        System.out.println("删除用户ID："+id);
        int i = userDao.delete(id);
        if (i > 0){
            return R.ok(id);
        }

        return R.ok(null);
    }
}
